package com.g8.pethospitallearnbackend.service.impls;

import com.g8.pethospitallearnbackend.entity.*;
import com.g8.pethospitallearnbackend.exception.CustomException;
import com.g8.pethospitallearnbackend.interceptors.AuthRequird;
import com.g8.pethospitallearnbackend.mapper.ExamMapper;
import com.g8.pethospitallearnbackend.mapper.PaperMapper;
import com.g8.pethospitallearnbackend.mapper.PaperQuestionMapper;
import com.g8.pethospitallearnbackend.mapper.QuestionMapper;
import com.g8.pethospitallearnbackend.service.PaperService;
import com.g8.pethospitallearnbackend.service.QuestionService;
import com.g8.pethospitallearnbackend.utils.NewIdGenerateUtil;
import com.g8.pethospitallearnbackend.utils.responseUtil.ResponseStatusEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class QuestionServieImpl implements QuestionService {
    @Autowired
    QuestionMapper questionMapper;

    @Autowired
    PaperQuestionMapper paperQuestionMapper;

    @Autowired
    PaperService paperService;

    @Autowired
    ExamMapper examMapper;

    @Override
    public List<Question> getAllQusetions() {
        QuestionExample questionExample = new QuestionExample();
        List<Question> questions = questionMapper.selectByExampleWithBLOBs(questionExample);
        return questions;
    }

    @Override
    public Question getQuesById(String quesId) {
        if (quesId == null || quesId.isEmpty()) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "请求ID为空，请补充完整！");
        }
        //QuestionExample questionExample = new QuestionExample();
        //questionExample.createCriteria().andQuesIdEqualTo(quesId);
        Question question = questionMapper.selectByPrimaryKey(quesId);
        if (question == null) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "查询的题目不存在，请重新查询");
        }
        return question;
    }

    //关键词搜索题目
    @Override
    public List<Question> searchQues(String searchQues) {
        //模糊搜索需要两边加% %
        searchQues = "%" + searchQues + "%";
        //Example类中的方法模糊搜索，除了TypeName那一项的其他都是自己加上的
        QuestionExample questionExample = new QuestionExample();
        questionExample.or().andTypeNameLike(searchQues);
        questionExample.or().andQuesDescLike(searchQues);
        questionExample.or().andQuesOpALike(searchQues);
        questionExample.or().andQuesOpBLike(searchQues);
        questionExample.or().andQuesOpCLike(searchQues);
        questionExample.or().andQuesOpDLike(searchQues);
        List<Question> questions = questionMapper.selectByExampleWithBLOBs(questionExample);
        if (questions.isEmpty()) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "搜索的题目不存在，请重新查询");
        }
        return questions;
    }

    //根据typeName，即题目的种类选择
    @Override
    public List<Question> selectByType(String typeName) {
        QuestionExample questionExample = new QuestionExample();
        questionExample.createCriteria().andTypeNameEqualTo(typeName);
        List<Question> questions = questionMapper.selectByExampleWithBLOBs(questionExample);
        if (questions.isEmpty()) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "搜索的题目不存在");
        }
        return questions;
    }

    @AuthRequird
    //新增一个题目
    @Override
    public Question addQues(Question question) {
        //判断传入的信息是不是完整的
        if (question.getQuesAns() == null || question.getQuesOpA() == null || question.getQuesDesc() == null
                || question.getTypeName() == null || question.getQuesAns().isEmpty()
                || question.getQuesOpA().isEmpty() || question.getQuesDesc().isEmpty()
                || question.getTypeName().isEmpty()) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "新增题目信息不完整，请补充完整后添加");
        }

        //判断传入的题目答案中是否有空的选项
        if (question.getQuesAns().contains("B") &&
                (question.getQuesOpB() == null || question.getQuesOpB().isEmpty())) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "您所填答案中含有空的选项，请修改");
        }
        if (question.getQuesAns().contains("C") &&
                (question.getQuesOpC() == null || question.getQuesOpC().isEmpty())) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "您所填答案中含有空的选项，请修改");
        }
        if (question.getQuesAns().contains("D") &&
                (question.getQuesOpD() == null || question.getQuesOpD().isEmpty())) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "您所填答案中含有空的选项，请修改");
        }

        //设置是否为单选，单选的话isSingle为1，多选为0
        if (question.getQuesAns().length() == 1) {
            question.setIsSingle((byte) 1);
        } else {
            question.setIsSingle((byte) 0);
        }

        // 随机生成id
        String id = NewIdGenerateUtil.getNumber(4);
        Question repeat = questionMapper.selectByPrimaryKey(id);
        while (repeat != null) {
            id = NewIdGenerateUtil.getNumber(4);
            repeat = questionMapper.selectByPrimaryKey(id);
        }
        question.setQuesId(id);

        questionMapper.insert(question);
        return question;

    }

    @Override
    public Question changeQues(Question question) {
        //判断传入的信息是不是完整的
        if (question.getQuesAns() == null || question.getQuesOpA() == null || question.getQuesDesc() == null
                || question.getTypeName() == null || question.getQuesAns().isEmpty()
                || question.getQuesOpA().isEmpty() || question.getQuesDesc().isEmpty()
                || question.getTypeName().isEmpty() || question.getQuesId() == null || question.getQuesId().isEmpty()) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "新增题目信息不完整，请补充完整后添加");
        }

        //查找是否有这个题目
        String quesId = question.getQuesId();
        Question question1 = questionMapper.selectByPrimaryKey(quesId);
        if (question1 == null) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "您要修改的题目不存在，请重新选择");
        }

        //判断传入的题目答案中是否有空的选项
        if (question.getQuesAns().contains("B") &&
                (question.getQuesOpB() == null || question.getQuesOpB().isEmpty())) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "您所填答案中含有空的选项，请修改");
        }
        if (question.getQuesAns().contains("C") &&
                (question.getQuesOpC() == null || question.getQuesOpC().isEmpty())) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "您所填答案中含有空的选项，请修改");
        }
        if (question.getQuesAns().contains("D") &&
                (question.getQuesOpD() == null || question.getQuesOpD().isEmpty())) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "您所填答案中含有空的选项，请修改");
        }

        //设置是否为单选，单选的话isSingle为1，多选为0
        if (question.getQuesAns().length() == 1) {
            question.setIsSingle((byte) 1);
        } else {
            question.setIsSingle((byte) 0);
        }

        //修改题目
        questionMapper.updateByPrimaryKeyWithBLOBs(question);

        return question;
    }

    @Override
    public String deleteQues(String quesId) {
        //查找数据库中是否存在要删除的题目
        Question question = questionMapper.selectByPrimaryKey(quesId);
        if (question == null) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "您所要删除的题目不存在，请重新选择");
        }
        //查看传入的quesId是否为空
        if (quesId == null || quesId.isEmpty()) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "您选择的quesId为空，请重新选择");
        }
        //处理paper中存在删除的题目的情况
        //在paper_question表中查找与要删除的question有关的paper
        PaperQuestionExample example = new PaperQuestionExample();
        example.createCriteria().andQuesIdEqualTo(quesId);
        List<PaperQuestion> paperQuestionList = paperQuestionMapper.selectByExample(example);

        for (int i = 0; i < paperQuestionList.size(); i++) {
            //拿到该paper
            String paperId = paperQuestionList.get(i).getPaperId();

            //查看该试卷是否被考试引用
            ExamExample examExample = new ExamExample();
            examExample.createCriteria().andPaperIdEqualTo(paperId);
            List<Exam> examList = examMapper.selectByExample(examExample);
            if (!examList.isEmpty()) {
                throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "您选择题目已经在考试中，不允许删除");
            }
        }

        //遍历查找出来的每一条记录，然后在有关的paper中删除该question，并改变总分
        for (int i = 0; i < paperQuestionList.size(); i++) {
            Integer score = paperQuestionList.get(i).getScore();
            //拿到该paper
            String paperId = paperQuestionList.get(i).getPaperId();
            Paper paper = paperService.getPaperById(paperId);

            //查看该试卷是否被考试引用
            ExamExample examExample = new ExamExample();
            examExample.createCriteria().andPaperIdEqualTo(paperId);
            List<Exam> examList = examMapper.selectByExample(examExample);
            if (!examList.isEmpty()) {
                throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "您选择题目已经在考试中，不允许删除");
            }

            //得到记载paper中的所有question的列表
            List<Paper.PaperQues> paperQuesList = paper.getPaperQuesList();
            //在列表中删除和question有关的一项
            for (int j = 0; j < paperQuesList.size(); j++) {
                Paper.PaperQues paperQues = paperQuesList.get(j);
                if (paperQues.getQuestion().getQuesId().equals(quesId)) {
                    paperQuesList.remove(j);
                }
            }
            paper.setPaperQuesList(paperQuesList);
            //重新设置题目的分数
            Integer paperScore = paper.getPaperScore();
            paper.setPaperScore(paperScore - score);

            //System.out.println(paper.getPaperScore());

//            for(int k=0;k<paperQuesList.size();k++){
//                System.out.println(paperQuesList.get(k).getQuestion().getQuesId()+paperQuesList.get(k).getScore());
//            }

            paperService.changePaper(paper);
        }
        //因为数据库中已经设置级联，那么就不用手动删除paper_question表中的数据了

        questionMapper.deleteByPrimaryKey(quesId);
        return "删除成功";
    }
}
